/**
 * @file thread10.c
 * @brief 传感器数据采集线程实现
 * 
 * 该线程负责定时采集各线程传感器数据，并提供快速访问接口。
 * 主要功能包括：
 * 1. 每3秒采集线程4、5、8、9的传感器数据
 * 2. 将采集的数据存储到全局数据结构中
 * 3. 提供线程安全的快速数据访问接口
 * 4. 支持线程6的快速数据获取需求
 * 
 * @author 伞控无人机项目组
 * @date 2024
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdbool.h>
#include "thread10.h"
#include "thread4.h"
#include "thread5.h"
#include "thread8.h"
#include "thread9.h"
#include "log_utils.h"
#include "log_modules.h"

// 配置常量
#define SENSOR_COLLECTION_INTERVAL 3        // 数据采集间隔（秒）
#define SENSOR_DATA_TIMEOUT 10              // 传感器数据超时时间（秒）
#define MAX_RETRY_COUNT 3                   // 最大重试次数

// 模块名称定义
#define THREAD10_MODULE LOG_MODULE_SENSOR

// 全局变量定义
static volatile int g_thread10_running = 1;  // 线程运行标志
global_sensor_snapshot_t g_sensor_snapshot;  // 全局传感器数据快照
pthread_rwlock_t g_sensor_snapshot_rwlock;  // 读写锁
// 固定启动基准时间，用于宽限期判断（避免使用会被更新的快照时间戳）
static time_t g_thread10_start_time = 0;

// 新增临时数据结构体，用于在锁外采集数据
typedef struct {
    prox_sensor_data_t prox1;
    prox_sensor_data_t prox2;
    nav_sensor_data_t navigation;
    rs485_sensor_data_t rs485;
} sensor_data_temp_t;

// 内部函数声明
static void collect_prox1_data_internal(prox_sensor_data_t *temp_data);
static void collect_prox2_data_internal(prox_sensor_data_t *temp_data);
static void collect_nav_data_internal(nav_sensor_data_t *temp_data);
static void collect_rs485_data_internal(rs485_sensor_data_t *temp_data);
static void collect_all_sensor_data(void);
static void update_global_timestamp(void);
static void log_sensor_data_update(sensor_type_t sensor_type);
static int check_sensor_data_timeout(time_t last_update);
static void check_sensor_data_timeouts(void);
static void safe_string_copy(char *dest, size_t dest_size, const char *src);

/**
 * @brief 尝试获取写锁，带超时机制
 * 
 * @param rwlock 读写锁指针
 * @param timeout_ms 超时时间（毫秒）
 * @return 成功返回0，超时返回-1
 */
int try_rwlock_wrlock_timeout(pthread_rwlock_t *rwlock, int timeout_ms) {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    
    // 计算超时时间
    ts.tv_nsec += timeout_ms * 1000000;
    if (ts.tv_nsec >= 1000000000) {
        ts.tv_sec += ts.tv_nsec / 1000000000;
        ts.tv_nsec %= 1000000000;
    }
    
    int ret = pthread_rwlock_timedwrlock(rwlock, &ts);
    if (ret == ETIMEDOUT) {
        return -1;  // 超时
    } else if (ret != 0) {
        LOG_ERROR(LOG_TO_FILE, THREAD10_MODULE, "写锁获取失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;  // 成功
}

/**
 * @brief 尝试获取读锁，带超时机制
 * 
 * @param rwlock 读写锁指针
 * @param timeout_ms 超时时间（毫秒）
 * @return 成功返回0，超时返回-1
 */
int try_rwlock_rdlock_timeout(pthread_rwlock_t *rwlock, int timeout_ms) {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    
    // 计算超时时间
    ts.tv_nsec += timeout_ms * 1000000;
    if (ts.tv_nsec >= 1000000000) {
        ts.tv_sec += ts.tv_nsec / 1000000000;
        ts.tv_nsec %= 1000000000;
    }
    
    int ret = pthread_rwlock_timedrdlock(rwlock, &ts);
    if (ret == ETIMEDOUT) {
        return -1;  // 超时
    } else if (ret != 0) {
        LOG_ERROR(LOG_TO_FILE, THREAD10_MODULE, "读锁获取失败: %s", strerror(ret));
        return -1;
    }
    
    return 0;  // 成功
}

// 传感器类型名称
static const char* sensor_type_names[] = {
    "PROX1",    // 接近传感器1
    "PROX2",    // 接近传感器2
    "NAV",      // 导航系统
    "RS485"     // RS485传感器
};

/**
 * @brief 安全的字符串复制函数
 */
static void safe_string_copy(char *dest, size_t dest_size, const char *src) {
    if (!dest || !src || dest_size == 0) {
        return;
    }
    
    // 使用snprintf确保字符串正确终止
    snprintf(dest, dest_size, "%s", src);
}

/**
 * @brief 初始化传感器数据快照
 */
static void init_sensor_snapshot(void) {
    // 初始化接近传感器1数据
    atomic_init(&g_sensor_snapshot.prox1.is_valid, false);
    g_sensor_snapshot.prox1.sensor_state = 0;
    g_sensor_snapshot.prox1.timestamp = 0;
    
    // 初始化接近传感器2数据
    atomic_init(&g_sensor_snapshot.prox2.is_valid, false);
    g_sensor_snapshot.prox2.sensor_state = 0;
    g_sensor_snapshot.prox2.timestamp = 0;
    
    // 初始化导航数据
    atomic_init(&g_sensor_snapshot.navigation.is_valid, false);
    memset(&g_sensor_snapshot.navigation, 0, sizeof(nav_sensor_data_t));
    
    // 初始化RS485传感器数据
    atomic_init(&g_sensor_snapshot.rs485.is_valid, false);
    memset(&g_sensor_snapshot.rs485, 0, sizeof(rs485_sensor_data_t));
    
    // 初始化统计信息
    atomic_init(&g_sensor_snapshot.total_sensors, SENSOR_COUNT);
    atomic_init(&g_sensor_snapshot.valid_sensors, 0);
    atomic_init(&g_sensor_snapshot.update_count, 0);
    
    g_sensor_snapshot.timestamp = time(NULL);
    
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "传感器数据快照初始化完成");
}

/**
 * @brief 批量采集所有传感器数据 (优化锁使用)
 */
static void collect_all_sensor_data(void) {
    // 创建临时数据结构，在锁外采集所有数据
    sensor_data_temp_t temp_data;
    
    // 在锁外采集所有传感器数据
    collect_prox1_data_internal(&temp_data.prox1);
    collect_prox2_data_internal(&temp_data.prox2);
    collect_nav_data_internal(&temp_data.navigation);
    collect_rs485_data_internal(&temp_data.rs485);
    
    // 只加一次写锁，快速更新全局数据
    pthread_rwlock_wrlock(&g_sensor_snapshot_rwlock);
    
    // 快速复制数据到全局结构
    g_sensor_snapshot.prox1 = temp_data.prox1;
    g_sensor_snapshot.prox2 = temp_data.prox2;
    g_sensor_snapshot.navigation = temp_data.navigation;
    g_sensor_snapshot.rs485 = temp_data.rs485;
    
    // 更新全局时间戳和统计信息
    update_global_timestamp();
    
    pthread_rwlock_unlock(&g_sensor_snapshot_rwlock);
    
    LOG_DEBUG(LOG_TO_CONSOLE_ONLY, THREAD10_MODULE, "批量传感器数据采集完成");
}

/**
 * @brief 采集接近传感器1数据 (内部函数，不加锁)
 */
static void collect_prox1_data_internal(prox_sensor_data_t *temp_data) {
    proximity_sensor_t prox_data;
    
    if (get_proximity_sensor_state(&prox_data) == 0) {
        temp_data->sensor_state = prox_data.sensor1_state;
        temp_data->timestamp = prox_data.timestamp;
        atomic_store(&temp_data->is_valid, true);
        log_sensor_data_update(SENSOR_PROX1);
    } else {
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, 
                 "获取接近传感器1数据失败，错误码: %d", errno);
        atomic_store(&temp_data->is_valid, false);
    }
}

/**
 * @brief 采集接近传感器2数据 (内部函数，不加锁)
 */
static void collect_prox2_data_internal(prox_sensor_data_t *temp_data) {
    proximity_sensor2_t prox_data;
    
    if (get_proximity_sensor2_state(&prox_data) == 0) {
        temp_data->sensor_state = prox_data.sensor2_state;
        temp_data->timestamp = prox_data.timestamp;
        atomic_store(&temp_data->is_valid, true);
        log_sensor_data_update(SENSOR_PROX2);
    } else {
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, 
                 "获取接近传感器2数据失败，错误码: %d", errno);
        atomic_store(&temp_data->is_valid, false);
    }
}

/**
 * @brief 采集导航数据 (内部函数，不加锁)
 */
static void collect_nav_data_internal(nav_sensor_data_t *temp_data) {
    nav_inspvaxa_data_t nav_data;
    
    if (get_nav_inspvaxa_data(&nav_data) == 0) {
        temp_data->latitude = nav_data.latitude;
        temp_data->longitude = nav_data.longitude;
        temp_data->altitude = nav_data.height;
        temp_data->heading = nav_data.azimuth;
        temp_data->pitch = nav_data.pitch;
        temp_data->roll = nav_data.roll;
        temp_data->north_velocity = nav_data.north_velocity;
        temp_data->east_velocity = nav_data.east_velocity;
        temp_data->up_velocity = nav_data.up_velocity;
        
        // 使用安全的字符串复制
        safe_string_copy(temp_data->ins_status, 
                        sizeof(temp_data->ins_status), 
                        nav_data.ins_status);
        safe_string_copy(temp_data->pos_status, 
                        sizeof(temp_data->pos_status), 
                        nav_data.pos_status);
        
        temp_data->timestamp = nav_data.timestamp;
        atomic_store(&temp_data->is_valid, true);
        
        log_sensor_data_update(SENSOR_NAV);
    } else {
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, 
                 "获取导航数据失败，错误码: %d", errno);
        atomic_store(&temp_data->is_valid, false);
    }
}

/**
 * @brief 采集RS485传感器数据 (内部函数，不加锁)
 */
static void collect_rs485_data_internal(rs485_sensor_data_t *temp_data) {
    anemometer_data_t anemometer_data;
    temp_humid_data_t temp_humid_data;
    force_sensor_data_t force_sensor_data[4];
    int success_count = 0;
    
    // 获取风速仪数据
    if (get_anemometer_data(&anemometer_data) == 0) {
        temp_data->wind_speed = anemometer_data.wind_speed;
        temp_data->wind_direction = anemometer_data.wind_direction;
        success_count++;
    } else {
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, 
                 "获取风速仪数据失败，错误码: %d", errno);
        temp_data->wind_speed = 0.0f;
        temp_data->wind_direction = 0.0f;
    }
    
    // 获取温湿度数据
    if (get_temp_humid_data(&temp_humid_data) == 0) {
        temp_data->temperature = temp_humid_data.temperature;
        temp_data->humidity = temp_humid_data.humidity;
        success_count++;
    } else {
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, 
                 "获取温湿度数据失败，错误码: %d", errno);
        temp_data->temperature = 0.0f;
        temp_data->humidity = 0.0f;
    }
    
    // 获取4个拉力传感器数据
    for (int i = 0; i < 4; i++) {
        if (get_force_sensor_data(i, &force_sensor_data[i]) == 0) {
            switch (i) {
                case 0:
                    temp_data->force_sensor1 = force_sensor_data[i].force;
                    break;
                case 1:
                    temp_data->force_sensor2 = force_sensor_data[i].force;
                    break;
                case 2:
                    temp_data->force_sensor3 = force_sensor_data[i].force;
                    break;
                case 3:
                    temp_data->force_sensor4 = force_sensor_data[i].force;
                    break;
            }
            success_count++;
        } else {
            LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, 
                     "获取拉力传感器%d数据失败，错误码: %d", i+1, errno);
            switch (i) {
                case 0:
                    temp_data->force_sensor1 = 0.0f;
                    break;
                case 1:
                    temp_data->force_sensor2 = 0.0f;
                    break;
                case 2:
                    temp_data->force_sensor3 = 0.0f;
                    break;
                case 3:
                    temp_data->force_sensor4 = 0.0f;
                    break;
            }
        }
    }
    
    // 设置时间戳和有效性
    temp_data->timestamp = time(NULL);
    
    // 如果至少有一个传感器数据获取成功，则认为数据有效
    if (success_count > 0) {
        atomic_store(&temp_data->is_valid, true);
        log_sensor_data_update(SENSOR_RS485);
    } else {
        atomic_store(&temp_data->is_valid, false);
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, "所有RS485传感器数据获取失败");
    }
}

/**
 * @brief 更新全局时间戳和统计信息 (内部函数，不加锁)
 */
static void update_global_timestamp(void) {
    g_sensor_snapshot.timestamp = time(NULL);
    
    // 计算有效传感器数量
    int valid_count = 0;
    if (atomic_load(&g_sensor_snapshot.prox1.is_valid)) valid_count++;
    if (atomic_load(&g_sensor_snapshot.prox2.is_valid)) valid_count++;
    if (atomic_load(&g_sensor_snapshot.navigation.is_valid)) valid_count++;
    if (atomic_load(&g_sensor_snapshot.rs485.is_valid)) valid_count++;
    
    atomic_store(&g_sensor_snapshot.valid_sensors, valid_count);
    atomic_fetch_add(&g_sensor_snapshot.update_count, 1);
    
    LOG_DEBUG(LOG_TO_CONSOLE_ONLY, THREAD10_MODULE, 
              "传感器数据更新完成，有效传感器: %d/%d", 
              valid_count, SENSOR_COUNT);
}

/**
 * @brief 检查传感器是否已经就绪（外部接口）
 * 
 * @return 1-传感器已就绪，0-传感器未就绪
 */
int check_sensors_ready(void) {
    // 在宽限期内也允许依据当前有效数据判定就绪
    //（宽限期只用于抑制超时告警，不强制未就绪）
    (void)g_thread10_start_time; // 明确使用全局基准，避免误用快照时间
    
    // 检查传感器就绪状态
    int ready_sensors = 0;
    int total_sensors = 0;
    
    // 检查接近传感器1（GPIO传感器，启动最快）
    if (atomic_load(&g_sensor_snapshot.prox1.is_valid)) {
        ready_sensors++;
    }
    total_sensors++;
    
    // 检查接近传感器2（GPIO传感器，启动最快）
    if (atomic_load(&g_sensor_snapshot.prox2.is_valid)) {
        ready_sensors++;
    }
    total_sensors++;
    
    // 检查RS485传感器（串口传感器，启动中等）
    if (atomic_load(&g_sensor_snapshot.rs485.is_valid)) {
        ready_sensors++;
    }
    total_sensors++;
    
    // 检查导航传感器（串口传感器，启动最慢，需要更多时间）
    if (atomic_load(&g_sensor_snapshot.navigation.is_valid)) {
        ready_sensors++;
    }
    total_sensors++;
    
    // 传感器就绪判断策略：
    // 1. 启动阶段：允许依据有效数据提前就绪
    // 2. 启动后：至少要有2个传感器正常工作（包括GPIO传感器）
    int min_required_sensors = 2;
    
    if (ready_sensors >= min_required_sensors) {
        return 1;  // 传感器已就绪
    }
    
    return 0;  // 传感器未就绪
}

/**
 * @brief 检查传感器数据是否超时
 */
static int check_sensor_data_timeout(time_t last_update) {
    time_t current_time = time(NULL);
    time_t startup_time = g_thread10_start_time;  // 使用固定启动时间作为宽限期基准
    
    // 启动阶段宽限期：在启动后的STARTUP_GRACE_PERIOD秒内不检查超时
    if ((current_time - startup_time) <= STARTUP_GRACE_PERIOD) {
        return 0;  // 启动阶段，不报告超时
    }
    
    return (current_time - last_update) > SENSOR_DATA_TIMEOUT;
}

/**
 * @brief 检查并处理传感器数据超时
 */
static void check_sensor_data_timeouts(void) {
    int timeout_count = 0;
    time_t current_time = time(NULL);
    time_t startup_time = g_thread10_start_time;
    
    // 检查是否还在启动阶段
    if ((current_time - startup_time) <= STARTUP_GRACE_PERIOD) {
        int remaining_time = STARTUP_GRACE_PERIOD - (current_time - startup_time);
        LOG_DEBUG(LOG_TO_CONSOLE_ONLY, THREAD10_MODULE, 
                 "启动阶段宽限期剩余 %d 秒，暂不检查传感器超时", remaining_time);
        return;  // 启动阶段，不检查超时
    }
    
    // 正常运行阶段，检查传感器超时
    LOG_DEBUG(LOG_TO_CONSOLE_ONLY, THREAD10_MODULE, "正常运行阶段，开始检查传感器超时");
    
    // 检查接近传感器1超时
    if (atomic_load(&g_sensor_snapshot.prox1.is_valid) && 
        check_sensor_data_timeout(g_sensor_snapshot.prox1.timestamp)) {
        atomic_store(&g_sensor_snapshot.prox1.is_valid, false);
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, "接近传感器1数据超时");
        timeout_count++;
    }
    
    // 检查接近传感器2超时
    if (atomic_load(&g_sensor_snapshot.prox2.is_valid) && 
        check_sensor_data_timeout(g_sensor_snapshot.prox2.timestamp)) {
        atomic_store(&g_sensor_snapshot.prox2.is_valid, false);
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, "接近传感器2数据超时");
        timeout_count++;
    }
    
    // 检查导航数据超时
    if (atomic_load(&g_sensor_snapshot.navigation.is_valid) && 
        check_sensor_data_timeout(g_sensor_snapshot.navigation.timestamp)) {
        atomic_store(&g_sensor_snapshot.navigation.is_valid, false);
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, "导航数据超时");
        timeout_count++;
    }
    
    // 检查RS485传感器数据超时
    if (atomic_load(&g_sensor_snapshot.rs485.is_valid) && 
        check_sensor_data_timeout(g_sensor_snapshot.rs485.timestamp)) {
        atomic_store(&g_sensor_snapshot.rs485.is_valid, false);
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, "RS485传感器数据超时");
        timeout_count++;
    }
    
    if (timeout_count > 0) {
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, 
                 "检测到 %d 个传感器数据超时，已标记为无效", timeout_count);
        
        // 重新计算有效传感器数量
        int valid_count = 0;
        if (atomic_load(&g_sensor_snapshot.prox1.is_valid)) valid_count++;
        if (atomic_load(&g_sensor_snapshot.prox2.is_valid)) valid_count++;
        if (atomic_load(&g_sensor_snapshot.navigation.is_valid)) valid_count++;
        if (atomic_load(&g_sensor_snapshot.rs485.is_valid)) valid_count++;
        
        atomic_store(&g_sensor_snapshot.valid_sensors, valid_count);
    }
}

/**
 * @brief 记录传感器数据更新日志
 */
static void log_sensor_data_update(sensor_type_t sensor_type) {
    if (sensor_type < SENSOR_COUNT) {
        LOG_DEBUG(LOG_TO_CONSOLE_ONLY, THREAD10_MODULE, 
                  "传感器 %s 数据更新完成", sensor_type_names[sensor_type]);
    }
}

/**
 * @brief 线程10主函数
 */
void *thread10_function(void *arg) {
    (void)arg;  // 避免未使用参数警告
    
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "线程10启动 - 传感器数据采集线程");
    // 记录固定启动时间基准
    g_thread10_start_time = time(NULL);
    
    // 初始化传感器数据快照
    init_sensor_snapshot();
    
    // 启动阶段：等待传感器线程完全就绪
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, 
             "启动阶段：等待传感器线程就绪，宽限期 %d 秒", STARTUP_GRACE_PERIOD);
    
    // 等待传感器就绪
    int startup_wait_count = 0;
    while (!check_sensors_ready() && g_thread10_running && startup_wait_count < STARTUP_GRACE_PERIOD) {
        LOG_DEBUG(LOG_TO_CONSOLE_ONLY, THREAD10_MODULE, 
                 "等待传感器就绪... (%d/%d)", startup_wait_count + 1, STARTUP_GRACE_PERIOD);
        
        // 每等待1秒，输出一次传感器状态
        if (startup_wait_count > 0) {
            LOG_DEBUG(LOG_TO_CONSOLE_ONLY, THREAD10_MODULE, 
                     "传感器状态检查: PROX1=%s, PROX2=%s, RS485=%s, NAV=%s", 
                     atomic_load(&g_sensor_snapshot.prox1.is_valid) ? "就绪" : "未就绪",
                     atomic_load(&g_sensor_snapshot.prox2.is_valid) ? "就绪" : "未就绪",
                     atomic_load(&g_sensor_snapshot.rs485.is_valid) ? "就绪" : "未就绪",
                     atomic_load(&g_sensor_snapshot.navigation.is_valid) ? "就绪" : "未就绪");
        }
        // 启动等待期间也执行一次采集，加速is_valid置位
        collect_all_sensor_data();
        
        sleep(1);
        startup_wait_count++;
    }
    
    if (check_sensors_ready()) {
        LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "传感器就绪检查完成，开始正常数据采集");
    } else {
        // 提供更详细的传感器状态信息
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, 
                 "启动阶段结束，传感器状态: PROX1=%s, PROX2=%s, RS485=%s, NAV=%s", 
                 atomic_load(&g_sensor_snapshot.prox1.is_valid) ? "就绪" : "未就绪",
                 atomic_load(&g_sensor_snapshot.prox2.is_valid) ? "就绪" : "未就绪",
                 atomic_load(&g_sensor_snapshot.rs485.is_valid) ? "就绪" : "未就绪",
                 atomic_load(&g_sensor_snapshot.navigation.is_valid) ? "就绪" : "未就绪");
        LOG_WARN(LOG_TO_FILE, THREAD10_MODULE, 
                 "部分传感器可能未完全就绪，但继续运行（将在后续检查中自动处理）");
    }
    
    // 主循环：每3秒采集一次所有传感器数据
    while (g_thread10_running) {
        LOG_DEBUG(LOG_TO_CONSOLE_ONLY, THREAD10_MODULE, "开始采集传感器数据...");
        
        // 批量采集所有传感器数据（优化锁使用）
        collect_all_sensor_data();
        
        // 检查传感器数据超时（启动阶段有宽限期）
        check_sensor_data_timeouts();
        
        // 等待下次采集
        sleep(SENSOR_COLLECTION_INTERVAL);
    }
    
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "线程10退出");
    return NULL;
}

/**
 * @brief 停止线程10
 */
void thread10_stop(void) {
    g_thread10_running = 0;
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "线程10停止信号已发送");
}

/**
 * @brief 检查线程10是否正在运行
 */
int thread10_is_running(void) {
    return g_thread10_running;
}

/**
 * @brief 获取传感器数据快照 (供线程6使用)
 */
int get_sensor_snapshot(global_sensor_snapshot_t *snapshot) {
    if (!snapshot) {
        return -1;
    }
    
    // 加读锁保护数据读取
    pthread_rwlock_rdlock(&g_sensor_snapshot_rwlock);
    
    // 复制数据快照
    memcpy(snapshot, &g_sensor_snapshot, sizeof(global_sensor_snapshot_t));
    
    pthread_rwlock_unlock(&g_sensor_snapshot_rwlock);
    
    return 0;
}

/**
 * @brief 获取接近传感器1数据
 */
int get_prox1_data(prox_sensor_data_t *data) {
    if (!data) {
        return -1;
    }
    
    pthread_rwlock_rdlock(&g_sensor_snapshot_rwlock);
    
    memcpy(data, &g_sensor_snapshot.prox1, sizeof(prox_sensor_data_t));
    
    pthread_rwlock_unlock(&g_sensor_snapshot_rwlock);
    
    return 0;
}

/**
 * @brief 获取接近传感器2数据
 */
int get_prox2_data(prox_sensor_data_t *data) {
    if (!data) {
        return -1;
    }
    
    pthread_rwlock_rdlock(&g_sensor_snapshot_rwlock);
    
    memcpy(data, &g_sensor_snapshot.prox2, sizeof(prox_sensor_data_t));
    
    pthread_rwlock_unlock(&g_sensor_snapshot_rwlock);
    
    return 0;
}

/**
 * @brief 获取导航数据
 */
int get_nav_data(nav_sensor_data_t *data) {
    if (!data) {
        return -1;
    }
    
    pthread_rwlock_rdlock(&g_sensor_snapshot_rwlock);
    
    memcpy(data, &g_sensor_snapshot.navigation, sizeof(nav_sensor_data_t));
    
    pthread_rwlock_unlock(&g_sensor_snapshot_rwlock);
    
    return 0;
}

/**
 * @brief 获取RS485传感器数据
 */
int get_rs485_data(rs485_sensor_data_t *data) {
    if (!data) {
        return -1;
    }
    
    pthread_rwlock_rdlock(&g_sensor_snapshot_rwlock);
    
    memcpy(data, &g_sensor_snapshot.rs485, sizeof(rs485_sensor_data_t));
    
    pthread_rwlock_unlock(&g_sensor_snapshot_rwlock);
    
    return 0;
}

/**
 * @brief 检查指定传感器数据是否有效
 */
int is_sensor_data_valid(sensor_type_t sensor_type) {
    if (sensor_type >= SENSOR_COUNT) {
        return 0;
    }
    
    int valid = 0;
    pthread_rwlock_rdlock(&g_sensor_snapshot_rwlock);
    
    switch (sensor_type) {
        case SENSOR_PROX1:
            valid = atomic_load(&g_sensor_snapshot.prox1.is_valid);
            break;
        case SENSOR_PROX2:
            valid = atomic_load(&g_sensor_snapshot.prox2.is_valid);
            break;
        case SENSOR_NAV:
            valid = atomic_load(&g_sensor_snapshot.navigation.is_valid);
            break;
        case SENSOR_RS485:
            valid = atomic_load(&g_sensor_snapshot.rs485.is_valid);
            break;
        default:
            valid = 0;
            break;
    }
    
    pthread_rwlock_unlock(&g_sensor_snapshot_rwlock);
    
    return valid;
}

/**
 * @brief 检查所有传感器数据是否有效
 */
int is_all_sensor_data_valid(void) {
    pthread_rwlock_rdlock(&g_sensor_snapshot_rwlock);
    
    int all_valid = (atomic_load(&g_sensor_snapshot.valid_sensors) == SENSOR_COUNT);
    
    pthread_rwlock_unlock(&g_sensor_snapshot_rwlock);
    
    return all_valid;
}

/**
 * @brief 调试函数：打印传感器数据
 */
void debug_sensor_data(void) {
    pthread_rwlock_rdlock(&g_sensor_snapshot_rwlock);
    
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "=== 传感器数据调试信息 ===");
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "总传感器数量: %d", atomic_load(&g_sensor_snapshot.total_sensors));
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "有效传感器数量: %d", atomic_load(&g_sensor_snapshot.valid_sensors));
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "更新计数: %d", atomic_load(&g_sensor_snapshot.update_count));
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "最后更新时间: %ld", g_sensor_snapshot.timestamp);
    
    pthread_rwlock_unlock(&g_sensor_snapshot_rwlock);
}

/**
 * @brief 打印传感器数据快照
 */
void print_sensor_snapshot(const global_sensor_snapshot_t *snapshot) {
    if (!snapshot) {
        return;
    }
    
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "=== 传感器数据快照 ===");
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "时间戳: %ld", snapshot->timestamp);
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "有效传感器: %d/%d", 
             atomic_load(&snapshot->valid_sensors), atomic_load(&snapshot->total_sensors));
    LOG_INFO(LOG_TO_FILE, THREAD10_MODULE, "更新计数: %d", atomic_load(&snapshot->update_count));
} 